package day09.handler.simpleChannelHandler;

import day09.packet.LoginRequestPacket;
import day09.packet.LoginResponsePacket;
import day09.util.LoginUtil;
import day09.util.PacketCodeC;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @author chenshijie
 * @date 2023/12/26 13:13
 */

public class LoginRequestHandler extends SimpleChannelInboundHandler<LoginRequestPacket> {

    private final static String USERNAME = "yu";
    private final static String PASSWORD = "password";

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestPacket loginRequestPacket) throws Exception {
        ctx.channel().writeAndFlush(login(ctx, loginRequestPacket));
    }

    private static boolean valid(LoginRequestPacket loginRequestPacket) {

        return USERNAME.equals(loginRequestPacket.getUsername()) && PASSWORD.equals(loginRequestPacket.getPassword());
    }

    private static LoginResponsePacket login(ChannelHandlerContext ctx, LoginRequestPacket loginRequestPacket) {
        LoginResponsePacket loginResponsePacket = new LoginResponsePacket();
        loginResponsePacket.setVersion(loginRequestPacket.getVersion());

        // 登录校验
        if (valid(loginRequestPacket)) {
            // 成功
            System.out.println("校验成功");
            loginResponsePacket.setStatus(200);
            loginResponsePacket.setMsg("登录成功");
            LoginUtil.markAsLogin(ctx.channel());

        } else {
            // 错误
            System.out.println("校验失败");
            loginResponsePacket.setStatus(405);
            loginResponsePacket.setMsg("密码错误或者账号不存在");
        }
        return loginResponsePacket;
    }
}
